<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>错误监控SDK示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        .demo-section {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 5px;
            border-radius: 3px;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        .error-btn {
            background: #dc3545;
        }
        .error-btn:hover {
            background: #c82333;
        }
        input {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 3px;
            padding: 10px;
            margin: 10px 0;
            max-height: 200px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <h1>前端异常监控SDK示例</h1>
    
    <div class="demo-section">
        <h2>SDK状态</h2>
        <div id="status">未初始化</div>
        <button onclick="initSDK()">初始化SDK</button>
        <button onclick="destroySDK()">销毁SDK</button>
    </div>

    <div class="demo-section">
        <h2>错误测试</h2>
        <button class="error-btn" onclick="throwError()">抛出JavaScript错误</button>
        <button class="error-btn" onclick="throwPromiseError()">抛出Promise错误</button>
        <button class="error-btn" onclick="loadFailedResource()">加载失败资源</button>
        <button onclick="reportCustomError()">上报自定义错误</button>
    </div>

    <div class="demo-section">
        <h2>性能测试</h2>
        <button onclick="getPerformance()">获取性能数据</button>
        <button onclick="reportCustomPerformance()">上报自定义性能数据</button>
    </div>

    <div class="demo-section">
        <h2>用户行为测试</h2>
        <input type="text" id="testInput" placeholder="输入测试内容">
        <button onclick="reportCustomBehavior()">上报自定义行为</button>
    </div>

    <div class="demo-section">
        <h2>事件日志</h2>
        <div id="log" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script type="module">
        // 模拟SDK模块（实际使用时需要引入真实的SDK）
        class MockErrorMonitorSDK {
            constructor() {
                this.isInitialized = false;
                this.config = null;
                this.eventListeners = {
                    error: [],
                    performance: [],
                    behavior: []
                };
            }

            init(config) {
                this.config = config;
                this.isInitialized = true;
                this.log('SDK初始化成功', config);
            }

            reportError(error, extra) {
                if (!this.isInitialized) {
                    this.log('SDK未初始化');
                    return;
                }
                const errorInfo = {
                    type: 'custom',
                    message: typeof error === 'string' ? error : error.message,
                    timestamp: Date.now(),
                    url: window.location.href,
                    userAgent: navigator.userAgent,
                    extra: extra
                };
                this.log('上报错误', errorInfo);
                this.emit('error', errorInfo);
            }

            reportPerformance(performance) {
                if (!this.isInitialized) {
                    this.log('SDK未初始化');
                    return;
                }
                this.log('上报性能数据', performance);
                this.emit('performance', performance);
            }

            reportBehavior(behavior) {
                if (!this.isInitialized) {
                    this.log('SDK未初始化');
                    return;
                }
                this.log('上报用户行为', behavior);
                this.emit('behavior', behavior);
            }

            on(event, listener) {
                this.eventListeners[event].push(listener);
            }

            off(event, listener) {
                const listeners = this.eventListeners[event];
                const index = listeners.indexOf(listener);
                if (index > -1) {
                    listeners.splice(index, 1);
                }
            }

            emit(event, data) {
                this.eventListeners[event].forEach(listener => {
                    try {
                        listener(data);
                    } catch (error) {
                        console.warn('事件监听器错误', error);
                    }
                });
            }

            getStatus() {
                return {
                    isInitialized: this.isInitialized,
                    config: this.config
                };
            }

            destroy() {
                this.isInitialized = false;
                this.config = null;
                this.eventListeners = {
                    error: [],
                    performance: [],
                    behavior: []
                };
                this.log('SDK已销毁');
            }

            log(message, data) {
                const logElement = document.getElementById('log');
                const timestamp = new Date().toLocaleTimeString();
                const logEntry = `[${timestamp}] ${message}${data ? ': ' + JSON.stringify(data, null, 2) : ''}`;
                logElement.innerHTML += logEntry + '\n';
                logElement.scrollTop = logElement.scrollHeight;
            }
        }

        // 创建全局SDK实例
        window.errorMonitor = new MockErrorMonitorSDK();

        // 添加事件监听器
        window.errorMonitor.on('error', (errorInfo) => {
            console.log('捕获到错误:', errorInfo);
        });

        window.errorMonitor.on('performance', (performanceInfo) => {
            console.log('性能数据:', performanceInfo);
        });

        window.errorMonitor.on('behavior', (behaviorInfo) => {
            console.log('用户行为:', behaviorInfo);
        });

        // 全局函数
        window.initSDK = function() {
            window.errorMonitor.init({
                reportUrl: 'https://api.example.com/error-report',
                appId: 'demo-app',
                appVersion: '1.0.0',
                userId: 'demo-user',
                enableConsole: true,
                enablePerformance: true,
                enableBehavior: true,
                sampleRate: 1.0,
                maxCacheSize: 100,
                reportInterval: 5000,
                tags: {
                    environment: 'demo',
                    version: '1.0.0'
                }
            });
            updateStatus();
        };

        window.destroySDK = function() {
            window.errorMonitor.destroy();
            updateStatus();
        };

        window.throwError = function() {
            throw new Error('这是一个测试错误');
        };

        window.throwPromiseError = function() {
            Promise.reject(new Error('这是一个Promise错误'));
        };

        window.loadFailedResource = function() {
            const img = new Image();
            img.src = 'https://example.com/nonexistent-image.jpg';
            img.onerror = function() {
                console.log('图片加载失败');
            };
        };

        window.reportCustomError = function() {
            window.errorMonitor.reportError('自定义错误消息', {
                severity: 'medium',
                component: 'demo-component'
            });
        };

        window.getPerformance = function() {
            const performance = {
                loadTime: performance.timing.loadEventEnd - performance.timing.navigationStart,
                domContentLoadedTime: performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart,
                timestamp: Date.now()
            };
            console.log('performance', performance)
            window.errorMonitor.reportPerformance(performance);
        };

        window.reportCustomPerformance = function() {
            window.errorMonitor.reportPerformance({
                loadTime: 1500,
                domContentLoadedTime: 800,
                fcp: 1200,
                lcp: 2500,
                fid: 50,
                cls: 0.1,
                timestamp: Date.now()
            });
        };

        window.reportCustomBehavior = function() {
            const input = document.getElementById('testInput');
            window.errorMonitor.reportBehavior({
                type: 'input',
                selector: '#testInput',
                text: input.value,
                url: window.location.href,
                timestamp: Date.now(),
                extra: {
                    inputType: 'text',
                    valueLength: input.value.length
                }
            });
        };

        window.clearLog = function() {
            document.getElementById('log').innerHTML = '';
        };

        function updateStatus() {
            const status = window.errorMonitor.getStatus();
            document.getElementById('status').innerHTML = `
                <strong>初始化状态:</strong> ${status.isInitialized ? '已初始化' : '未初始化'}<br>
                <strong>配置:</strong> ${status.config ? JSON.stringify(status.config, null, 2) : '无'}
            `;
        }

        // 初始化状态显示
        updateStatus();
    </script>
</body>
</html> 